package com.qding.park.common.utils.rchl;



import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.UnsupportedEncodingException;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.Random;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class RchlCommonUtil {

	private static final Log _log = LogFactory.getLog(RchlCommonUtil.class);

	
	public static  int getMethodFlag(){
		
		String flag = RchlPropertiesUtil.getValue("islocate");
		return Integer.parseInt(flag);
		
	}
	
	public static String getRandomChar(int pwd_len) {
		int i; // 
		int count = 0; // 
		char[] str = { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k',
				'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w',
				'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8',
				'9', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K',
				'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W',
				'X', 'Y', 'Z' };

		StringBuffer pwd = new StringBuffer("");
		Random r = new Random();
		while (count < pwd_len) {
			i = Math.abs(r.nextInt(str.length)); 

			if (i >= 0 && i < str.length) {
				pwd.append(str[i]);
				count++;
			}
		}
		return pwd.toString();
	}

	
	public static String toUTF8(String keyword) {
		StringBuffer sb = new StringBuffer();
		for (int i = 0; i < keyword.length(); i++) {
			char c = keyword.charAt(i);
			if (c >= 0 && c <= 255) {
				sb.append(c);
			} else {
				byte[] b;
				try {
					b = Character.toString(c).getBytes("utf-8");
				} catch (UnsupportedEncodingException e) {
					e.printStackTrace();
					b = new byte[0];
				}
				for (int j = 0; j < b.length; j++) {
					int k = b[j];
					if (k < 0) {
						k += 256;
					}
					sb.append("%" + Integer.toHexString(k).toUpperCase());

				}
			}
		}
		return sb.toString();
	}

	
	public static String getRandomNumber(int pwd_len) {
		int i;
		int count = 0; 
		char[] str = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' };

		StringBuffer pwd = new StringBuffer("");
		Random r = new Random();
		while (count < pwd_len) {
			
			i = Math.abs(r.nextInt(str.length)); 

			if (i >= 0 && i < str.length) {
				pwd.append(str[i]);
				count++;
			}
		}
		return pwd.toString();
	}

	

	public static String inputStreamToString(InputStream inputStream) {
		try {
			BufferedInputStream bio = new BufferedInputStream(inputStream);

			int len = bio.available();
			byte datas[] = new byte[len];
			int actual = 0;
			int bytesread = 0;
			while ((bytesread != len) && (actual != -1)) {
				actual = bio.read(datas, bytesread, len - bytesread);
				bytesread += actual;
			}
			String returnValueTemp = new String(datas, "UTF-8");
			bio.close();
			inputStream.close();

			return returnValueTemp;
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			return null;
		}

	}

	

	@SuppressWarnings("unused")
	public synchronized static String getUniqueNumber() {
		String returnStr = "";
		String index[] = { "a", "b", "c", "d", "e", "f", "g", "h", "i", "j",
				"k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v",
				"w", "x", "y", "z" };
		int last = 1;

		return returnStr;
	}

	public static double getContentLength(String content) {
		int length = content.getBytes().length;
		return length;
	}
	
	/**
	 * 
	 * @return
	 */
	public static String getClientType(String clientId){
		int index = clientId.indexOf("_");
		if(index <0){
			return "android";
		}
		String flagStr = clientId.substring(0, index);
		if("AD".equalsIgnoreCase(flagStr)){
			return "android";
		}else if("IPad".equalsIgnoreCase(flagStr) || "IP".equalsIgnoreCase(flagStr)){
			return "ios";
		}else{
			return "android";
		}
	}

	
	
	/**
	 * 
	 * @return
	 * @author YY
	 * @date 2013-12-10
	 * @version V3.0
	 * @history
		  1.modified by YY at 2013-12-10
	 */
	public static List<String> getAllLocalIPs() {
		List<String> ipList = new ArrayList<String>();
		Enumeration<NetworkInterface> allNetInterfaces = null;
		try {
			allNetInterfaces = NetworkInterface.getNetworkInterfaces();
		} catch (SocketException e) {
			return ipList;
		}
		
		InetAddress ip = null;
		
		while (allNetInterfaces != null && allNetInterfaces.hasMoreElements()) {
			NetworkInterface netInterface = (NetworkInterface) allNetInterfaces.nextElement();
			Enumeration<InetAddress> addresses = netInterface.getInetAddresses();
			
			while (addresses.hasMoreElements()) {
				ip = (InetAddress) addresses.nextElement();
				if(ip!= null &&  ip instanceof Inet4Address) {
					if(!ip.toString().contains("127.0.0.1")) {
						ipList.add(ip.toString().replaceAll("/", ""));
					}
				}
			}
		}
		
		return ipList;
	}

	
	public static byte[] objToBytes(java.lang.Object obj){
		
		if(null == obj){
			return  null;
		}
		
		byte [] bytes =  new byte[1024];
		ByteArrayOutputStream byteArrayOutputStream = null;
		ObjectOutputStream objectOutputStream = null;
		
		try {
			byteArrayOutputStream  = new ByteArrayOutputStream();
			objectOutputStream = new ObjectOutputStream(byteArrayOutputStream);
			objectOutputStream.writeObject(obj);
			bytes = byteArrayOutputStream.toByteArray();
			return bytes;
		} catch (Exception e) {
			_log.error(e.getMessage(),e);
			_log.info("###### get bytes  from object error");
			return null;
		}finally{
			try {
				byteArrayOutputStream.close();
				objectOutputStream.close();
			} catch (Exception e2) {
				_log.error(e2.getMessage(),e2);
			}
			
		}
		
	}
	
	
	public static java.lang.Object bytesToObj(byte [] bytes){
		
		ByteArrayInputStream byteArrayInputStream = null;
		ObjectInputStream objectInputStream = null;
		if(null  == bytes){
			return null;
		}
		try {
			 java.lang.Object obj = new java.lang.Object();
			 byteArrayInputStream  = new ByteArrayInputStream(bytes);
			 objectInputStream = new ObjectInputStream(byteArrayInputStream);
			 obj = objectInputStream.readObject();
			 
			 return obj;
		} catch (Exception e) {
			// TODO: handle exception
			_log.error(e.getMessage(),e);
			_log.info("###### get object data from bytes error");
			return null;
		}finally{
			try {
				 byteArrayInputStream.close();
				 objectInputStream.close();
			} catch (Exception e2) {
				_log.error(e2.getMessage(),e2);
			}
		}
		
	}
	
	public static java.lang.Object bytesToObj(InputStream inputStream){
		
		if(null == inputStream){
			return null;
		}
		ObjectInputStream objectInputStream = null;
		try {
			 java.lang.Object obj = new java.lang.Object();
			 
			 objectInputStream = new ObjectInputStream(inputStream);
			 
			 obj = objectInputStream.readObject();
			 
			 return obj;
		} catch (Exception e) {
			// TODO: handle exception
			_log.error(e.getMessage(),e);
			_log.info("###### get object data from bytes error");
			e.printStackTrace();
			return null;
		}finally{
			try {
				 objectInputStream.close();
				 inputStream.close();
			} catch (Exception e2) {
				_log.error(e2.getMessage(),e2);
			}
		}
		
	}
	
	
	
	public static void main(String args[]) {
		//System.out.println(createNeedLengthString(null,10).getBytes().length);
	}
}
